package com.coocaa.ops.api.v1.content.util;

import com.coocaa.ops.api.common.constant.PolicyGroupCategory;
import com.coocaa.ops.api.common.model.HeaderModel;
import com.coocaa.ops.api.v1.content.model.query.PanelQueryModel;
import com.coocaa.ops.api.v1.content.model.query.TabQueryModel;
import com.coocaa.ops.api.v1.content.model.query.TabStreamQueryModel;
import com.coocaa.ops.api.v1.policy.model.PolicyModel;

/**
 * @author tangminghong
 * @date 2020-06-28
 */
public class TabContentQueryUtil {

    private static final int DEFAULT_PAGE_SIZE = 6;

    public static TabQueryModel buildTabQueryModel(TabQueryModel origQueryModel, HeaderModel header, PolicyModel policy) {
        origQueryModel.setHeader(header);
        origQueryModel.setPolicyCategory(policy != null ? policy.getCategory() : null);
        return origQueryModel;
    }

    public static PanelQueryModel buildPanelQueryModel(TabQueryModel queryModel) {
        PanelQueryModel result = new PanelQueryModel();
        result.setLimit(DEFAULT_PAGE_SIZE);
        result.setOffset(0);
        if (queryModel == null) {
            return result;
        }
        result.setTabId(Integer.parseInt(queryModel.getTabId()));
        result.setPolicyCategory(queryModel.getPolicyCategory());
        result.setHeader(queryModel.getHeader());
        handleLimitAndOffset(result, queryModel);
        return result;
    }

    public static TabStreamQueryModel buildTabStreamQueryModel(TabQueryModel queryModel) {
        TabStreamQueryModel result = new TabStreamQueryModel();
        result.setLimit(DEFAULT_PAGE_SIZE);
        result.setOffset(0);
        if (queryModel == null) {
            return result;
        }
        handleLimitAndOffset(result, queryModel);
        return result;
    }

    private static void handleLimitAndOffset(PanelQueryModel panelQueryModel, TabQueryModel tabQueryModel) {
        Integer page = tabQueryModel.getPage();
        Integer pageSize = tabQueryModel.getPageSize();
        page = (page != null) ? page-1 : 0;
        page = page < 0 ? 0 : page;
        pageSize = pageSize != null ? pageSize : DEFAULT_PAGE_SIZE;
        pageSize = pageSize <= 0 ? DEFAULT_PAGE_SIZE : pageSize;

        panelQueryModel.setLimit(pageSize);
        panelQueryModel.setOffset(pageSize * page);

    }

    private static void handleLimitAndOffset(TabStreamQueryModel panelQueryModel, TabQueryModel tabQueryModel) {
        Integer page = tabQueryModel.getPage();
        Integer pageSize = tabQueryModel.getPageSize();
        page = (page != null) ? page-1 : 0;
        page = page < 0 ? 0 : page;
        pageSize = pageSize != null ? pageSize : DEFAULT_PAGE_SIZE;
        pageSize = pageSize <= 0 ? DEFAULT_PAGE_SIZE : pageSize;

        panelQueryModel.setLimit(pageSize);
        panelQueryModel.setOffset(pageSize * page);

    }
}
